import {routerMap, routes} from "../../router/router";

/**
 * 不需要权限控制
 */
const state = {
	routers: routes,
	hasGetRules: false
};

const mutations = {
	CONCAT_ROUTES(state, routeList) {
		// 注意合并顺序
		state.routers = routeList.concat(routes);
		state.hasGetRules = true;
	}
};

/**
 * 递归
 */
const getAccessRouterList = (routes, rules) => {
	return routes.filter(item => {
		if (rules[item.name]) {
			if (item.children) item.children = getAccessRouterList(item.children, rules);
			return true;
		} else return false;
	});
};

const actions = {
	concatRoutes({commit}, rules) {
		return new Promise(((resolve, reject) => {
			try {
				let rulesList;
				//Object.entries对象转数组
				if (Object.entries(rules).every(item => item[1])) {
					rulesList = routerMap;
				} else {
					rulesList = getAccessRouterList(routerMap, rules);
				}
				commit('CONCAT_ROUTES', rulesList);
				resolve(state.routers);
			} catch (e) {
				reject(e);
			}
		}));
	}
};

export default {
	state, mutations, actions
};
